/*
 * @Descripttion: 组件业务名
 * @version:
 * @Author: lhl
 * @Date: 2024-11-18 12:59:58
 * @LastEditors: lhl
 * @LastEditTime: 2024-11-18 23:40:53
 */
import React from 'react';
import { Breadcrumb } from 'antd';
import type { BreadcrumbItemProps } from 'antd/es/breadcrumb';
import { useLocation, Link } from 'react-router-dom';
import { useAppSelector } from '@/hooks/store';
import './index.module.less';

const BreadCrumb: React.FC = () => {
  const location = useLocation();
  const menuList = useAppSelector((state) => state.menu.menuList);

  const getBreadcrumbItems = () => {
    const pathSnippets = location.pathname.split('/').filter((i) => i);
    const breadcrumbItems: BreadcrumbItemProps[] = [];

    let currentPath = '';

    pathSnippets.forEach((snippet, index) => {
      currentPath += `/${snippet}`;
      const menuItem = findMenuItemByPath(currentPath, menuList);

      if (menuItem) {
        breadcrumbItems.push({
          children:
            index === pathSnippets.length - 1 ? (
              menuItem.meta.title
            ) : (
              <Link to={currentPath}>{menuItem.meta.title}</Link>
            ),
        });
      }
    });

    return breadcrumbItems;
  };

  const findMenuItemByPath = (path: string, menus: any[]): any => {
    for (const menu of menus) {
      if (menu.path === path) return menu;
      if (menu.children) {
        const found = findMenuItemByPath(path, menu.children);
        if (found) return found;
      }
    }
    return null;
  };

  return (
    <Breadcrumb
      items={getBreadcrumbItems().map((item) => ({
        title: item.children,
      }))}
    />
  );
};

export default BreadCrumb;
